//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package dev_container_api_serv

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/dev_container_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/dev_container_api"
)

type DevContainerApiImpl struct {
	dev_container_api.UnimplementedDevContainerApiServer
}

func (apiImpl *DevContainerApiImpl) ListPackage(ctx context.Context, req *dev_container_api.ListPackageRequest) (*dev_container_api.ListPackageResponse, error) {
	pkgItemList, err := dev_container_dao.PkgDao.List(ctx)
	if err != nil {
		return nil, err
	}

	pkgList := []*dev_container_api.PackageInfo{}
	for _, pkgItem := range pkgItemList {
		pkgList = append(pkgList, pkgItem.ToPackageInfo())
	}

	return &dev_container_api.ListPackageResponse{
		Code:        dev_container_api.ListPackageResponse_CODE_OK,
		PackageList: pkgList,
	}, nil
}

func (apiImpl *DevContainerApiImpl) ListPackageVersion(ctx context.Context, req *dev_container_api.ListPackageVersionRequest) (*dev_container_api.ListPackageVersionResponse, error) {
	emptyList := []string{}

	exist, err := dev_container_dao.PkgDao.Exist(ctx, req.PackageName)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &dev_container_api.ListPackageVersionResponse{
			Code:        dev_container_api.ListPackageVersionResponse_CODE_NO_PACKAGE,
			ErrMsg:      "软件包不存在",
			VersionList: emptyList,
		}, nil
	}

	verItemList, err := dev_container_dao.PkgVerDao.ListByPkgName(ctx, req.PackageName)
	if err != nil {
		return nil, err
	}
	verList := []string{}
	for _, verItem := range verItemList {
		verList = append(verList, verItem.Version)
	}
	return &dev_container_api.ListPackageVersionResponse{
		Code:        dev_container_api.ListPackageVersionResponse_CODE_OK,
		VersionList: verList,
	}, nil
}
